import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { useSearchParams } from 'react-router-dom'
import { patientCircleService, handleApiResponse, handleApiError } from '../../../utils/api'
import TopNav from '../../../components/topNav'
import type { PatientSickCircleItem } from '../../../type/store'
import './index.css'
import der_jia from '../../../assets/hdpi/der_jia.jpg'
interface UserInfo {
  userId: number
  nickname: string
  avatar: string
  gender: number
}

const Index: React.FC = () => {
  const [searchParams] = useSearchParams()
  const patientUserId = searchParams.get('patientUserId')
  
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null)
  const [postList, setPostList] = useState<PatientSickCircleItem[]>([])
  const [loading, setLoading] = useState(true)
  const [postLoading, setPostLoading] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMorePosts, setHasMorePosts] = useState(true)

  // 获取用户信息（这里需要根据实际API调整）
  const fetchUserInfo = useCallback(async () => {
    if (!patientUserId) return
    
    try {
      // 这里应该调用获取用户信息的API，暂时使用模拟数据
      const mockUserInfo: UserInfo = {
        userId: Number(patientUserId),
        nickname: '小悦悦',
        avatar: '/default-avatar.png',
        gender: 1
      }
      setUserInfo(mockUserInfo)
    } catch (error) {
      console.error('获取用户信息失败:', handleApiError(error))
    }
  }, [patientUserId])

  // 获取用户发帖列表
  const fetchPostList = useCallback(async (page: number = 1, isLoadMore: boolean = false) => {
    if (!patientUserId) return
    
    try {
      setPostLoading(true)
      const response = await patientCircleService.getPatientSickCircleList({
        patientUserId: Number(patientUserId),
        page,
        count: 10
      })
      
      const result = handleApiResponse<PatientSickCircleItem[]>(response)
      
      if (isLoadMore) {
        setPostList(prev => [...prev, ...result])
      } else {
        setPostList(result)
      }
      
      // 判断是否还有更多帖子
      setHasMorePosts(result.length === 10)
      setCurrentPage(page)
    } catch (error) {
      console.error('获取发帖列表失败:', handleApiError(error))
    } finally {
      setPostLoading(false)
    }
  }, [patientUserId])

  // 加载更多帖子
  const loadMorePosts = () => {
    if (!postLoading && hasMorePosts) {
      fetchPostList(currentPage + 1, true)
    }
  }

  // 计算属性：是否可以加载更多帖子
  const canLoadMorePosts = useMemo(() => {
    return !postLoading && hasMorePosts
  }, [postLoading, hasMorePosts])

  // 计算属性：用户性别显示
  const genderSymbol = useMemo(() => {
    return userInfo?.gender === 1 ? '♂' : '♀'
  }, [userInfo?.gender])

  // 计算属性：性别图标样式类名
  const genderIconClass = useMemo(() => {
    return userInfo?.gender === 1 ? 'male' : 'female'
  }, [userInfo?.gender])

  useEffect(() => {
    if (patientUserId) {
      const loadData = async () => {
        await fetchUserInfo()
        await fetchPostList(1, false)
        setLoading(false)
      }
      loadData()
    }
  }, [patientUserId, fetchUserInfo, fetchPostList])

  if (loading) {
    return <div className="loading">加载中...</div>
  }

  if (!userInfo) {
    return <div className="error">用户信息加载失败</div>
  }

  return (
    <div className="people-comment-list">
      {/* 头部导航 */}
      <TopNav title="用户发帖" />
      
      {/* 页面内容区域 */}
      <div className="people-comment-content">
        {/* 头部背景图片 */}
        <div className="header-bg">
          <img src={der_jia} alt="背景图" className="bg-image" />
        </div>
      
      {/* 用户信息区域 */}
      <div className="user-info-section">
        <div className="user-avatar-container">
          <img 
            src={userInfo.avatar || '/default-avatar.png'} 
            alt="用户头像" 
            className="user-avatar"
          />
          <div className={`gender-icon ${genderIconClass}`}>
            {genderSymbol}
          </div>
        </div>
        <div className="user-name">{userInfo.nickname}</div>
      </div>
      
      {/* 发帖列表标题 */}
      <div className="section-title">
        <div className="title-bar"></div>
        <span className="title-text">他发布的病友圈</span>
      </div>
      
      {/* 发帖列表 */}
      <div className="post-list">
        {postLoading && postList.length === 0 ? (
          <div className="post-loading">加载发帖中...</div>
        ) : (
          <>
            {postList.map((post) => (
              <div key={post.sickCircleId} className="post-card">
                <div className="post-title">{post.title}</div>
                <div className="post-date">
                  {new Date(post.releaseTime).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                  })}
                </div>
                <div className="post-content">{post.detail}</div>
                <div className="post-stats">
                  <span className="stat-item">收藏 {post.collectionNum}</span>
                  <span className="stat-item">建议 {post.commentNum}</span>
                </div>
              </div>
            ))}
            
            {postList.length === 0 && !postLoading && (
              <div className="no-posts">暂无发帖</div>
            )}
            
            {canLoadMorePosts && postList.length > 0 && (
              <div className="load-more">
                <button 
                  className="load-more-btn" 
                  onClick={loadMorePosts}
                  disabled={postLoading}
                >
                  {postLoading ? '加载中...' : '加载更多'}
                </button>
              </div>
            )}
          </>
        )}
      </div>
      </div>
    </div>
  )
}

export default Index